<script setup>
import {ref, onBeforeUnmount, watch, computed} from 'vue';
import {StopCircle, Clock, Trophy, Star, Target} from 'lucide-vue-next';
import {useI18n} from "vue-i18n";

const {t} = useI18n({
  useScope: 'local'
});

const COLORS = computed(() => [t('colors.red'), t('colors.blue'), t('colors.green'), t('colors.yellow')]);
const COLOR_MAP = computed(() => ({
  [t('colors.red')]: 'text-red-500',
  [t('colors.blue')]: 'text-blue-500',
  [t('colors.green')]: 'text-green-500',
  [t('colors.yellow')]: 'text-yellow-500'
}));
const NEUTRAL_WORDS = computed(() => [t('neutralWords.star'), t('neutralWords.house'), t('neutralWords.table'), t('neutralWords.flower')]);

const PRACTICE_TRIALS = 12;
const TEST_TRIALS = 72;

const emit = defineEmits(['complete']);

const stage = ref('instructions');
const currentTrialIndex = ref(0);
const trials = ref([]);
const responses = ref([]);
const reactionTimes = ref([]);
const accuracy = ref([]);
const timeLeft = ref(360);
const startTime = ref(0);
const trialStartTime = ref(0);
const score = ref(0);
const isPractice = ref(false);

let timerInterval = null;

const trial = computed(() => trials.value[currentTrialIndex.value]);

const generateTrials = (count) => {
  const newTrials = [];
  const conditionsPerBlock = Math.floor(count / 3);
  for (let i = 0; i < conditionsPerBlock; i++) {
    const color = COLORS.value[Math.floor(Math.random() * COLORS.value.length)];
    newTrials.push({
      id: newTrials.length + 1,
      word: color,
      color: color,
      condition: 'congruent',
      correctResponse: color
    });
  }
  for (let i = 0; i < conditionsPerBlock; i++) {
    const wordColor = COLORS.value[Math.floor(Math.random() * COLORS.value.length)];
    let displayColor = COLORS.value[Math.floor(Math.random() * COLORS.value.length)];
    while (displayColor === wordColor) {
      displayColor = COLORS.value[Math.floor(Math.random() * COLORS.value.length)];
    }
    newTrials.push({
      id: newTrials.length + 1,
      word: wordColor,
      color: displayColor,
      condition: 'incongruent',
      correctResponse: displayColor
    });
  }
  for (let i = 0; i < count - conditionsPerBlock * 2; i++) {
    const word = NEUTRAL_WORDS.value[Math.floor(Math.random() * NEUTRAL_WORDS.value.length)];
    const color = COLORS.value[Math.floor(Math.random() * COLORS.value.length)];
    newTrials.push({id: newTrials.length + 1, word: word, color: color, condition: 'neutral', correctResponse: color});
  }
  for (let i = newTrials.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [newTrials[i], newTrials[j]] = [newTrials[j], newTrials[i]];
  }
  return newTrials;
};

const handleStartPractice = () => {
  stage.value = 'practice';
  isPractice.value = true;
  trials.value = generateTrials(PRACTICE_TRIALS);
  currentTrialIndex.value = 0;
  trialStartTime.value = Date.now();
};

const handleStartTest = () => {
  stage.value = 'test';
  isPractice.value = false;
  startTime.value = Date.now();
  trials.value = generateTrials(TEST_TRIALS);
  currentTrialIndex.value = 0;
  responses.value = [];
  reactionTimes.value = [];
  accuracy.value = [];
  score.value = 0;
  trialStartTime.value = Date.now();
};

const handleColorResponse = (selectedColor) => {
  const reactionTime = Date.now() - trialStartTime.value;
  const correct = selectedColor === trial.value.correctResponse;

  if (!isPractice.value) {
    responses.value.push(selectedColor);
    reactionTimes.value.push(reactionTime);
    accuracy.value.push(correct);
    if (correct) score.value++;
  }

  if (currentTrialIndex.value < trials.value.length - 1) {
    currentTrialIndex.value++;
    trialStartTime.value = Date.now();
  } else {
    if (isPractice.value) {
      handleStartTest();
    } else {
      stage.value = 'results';
    }
  }
};

const handleComplete = () => {
  const totalCorrect = accuracy.value.filter(a => a).length;
  const overallAccuracy = accuracy.value.length > 0 ? Math.round((totalCorrect / accuracy.value.length) * 100) : 0;

  const congruentTrials = trials.value.filter(t => t.condition === 'congruent');
  const incongruentTrials = trials.value.filter(t => t.condition === 'incongruent');

  const congruentAccuracy = congruentTrials.length > 0 ? Math.round((accuracy.value.filter((a, i) => trials.value[i].condition === 'congruent' && a).length / congruentTrials.length) * 100) : 0;
  const incongruentAccuracy = incongruentTrials.length > 0 ? Math.round((accuracy.value.filter((a, i) => trials.value[i].condition === 'incongruent' && a).length / incongruentTrials.length) * 100) : 0;

  const congruentRTs = reactionTimes.value.filter((rt, i) => trials.value[i].condition === 'congruent');
  const incongruentRTs = reactionTimes.value.filter((rt, i) => trials.value[i].condition === 'incongruent');

  const avgCongruentRT = congruentRTs.length > 0 ? Math.round(congruentRTs.reduce((sum, rt) => sum + rt, 0) / congruentRTs.length) : 0;
  const avgIncongruentRT = incongruentRTs.length > 0 ? Math.round(incongruentRTs.reduce((sum, rt) => sum + rt, 0) / incongruentRTs.length) : 0;

  const stroopEffect = avgIncongruentRT - avgCongruentRT;
  const inhibitionScore = Math.max(0, Math.min(100, Math.round(overallAccuracy - (stroopEffect / 10))));

  const timeUsed = Math.round((Date.now() - startTime.value) / 1000);

  const result = {
    id: Date.now().toString(),
    testType: 'inhibitory-control',
    score: inhibitionScore,
    completedAt: new Date(),
    duration: timeUsed,
    details: {
      totalTrials: trials.value.length,
      correctResponses: totalCorrect,
      overallAccuracy,
      congruentAccuracy,
      incongruentAccuracy,
      stroopEffect,
      averageReactionTime: reactionTimes.value.length > 0 ? Math.round(reactionTimes.value.reduce((sum, rt) => sum + rt, 0) / reactionTimes.value.length) : 0,
      inhibitionIndex: Math.round(100 - (stroopEffect / 10))
    }
  };

  emit('complete', result);
};

watch(stage, (newStage) => {
  if (newStage === 'test') {
    timerInterval = setInterval(() => {
      if (timeLeft.value <= 1) {
        stage.value = 'results';
      } else {
        timeLeft.value--;
      }
    }, 1000);
  } else {
    clearInterval(timerInterval);
  }
});

onBeforeUnmount(() => {
  clearInterval(timerInterval);
});

const progress = computed(() => (currentTrialIndex.value / trials.value.length) * 100);

const finalResult = computed(() => {
  if (stage.value !== 'results') return {};
  const totalCorrect = accuracy.value.filter(a => a).length;
  const overallAccuracy = accuracy.value.length > 0 ? Math.round((totalCorrect / accuracy.value.length) * 100) : 0;
  const congruentTrials = trials.value.filter(t => t.condition === 'congruent');
  const incongruentTrials = trials.value.filter(t => t.condition === 'incongruent');
  const congruentAccuracy = congruentTrials.length > 0 ? Math.round((accuracy.value.filter((a, i) => trials.value[i].condition === 'congruent' && a).length / congruentTrials.length) * 100) : 0;
  const incongruentAccuracy = incongruentTrials.length > 0 ? Math.round((accuracy.value.filter((a, i) => trials.value[i].condition === 'incongruent' && a).length / incongruentTrials.length) * 100) : 0;
  const congruentRTs = reactionTimes.value.filter((rt, i) => trials.value[i].condition === 'congruent');
  const incongruentRTs = reactionTimes.value.filter((rt, i) => trials.value[i].condition === 'incongruent');
  const avgCongruentRT = congruentRTs.length > 0 ? Math.round(congruentRTs.reduce((sum, rt) => sum + rt, 0) / congruentRTs.length) : 0;
  const avgIncongruentRT = incongruentRTs.length > 0 ? Math.round(incongruentRTs.reduce((sum, rt) => sum + rt, 0) / incongruentRTs.length) : 0;
  const stroopEffect = avgIncongruentRT - avgCongruentRT;
  const inhibitionScore = Math.max(0, Math.min(100, Math.round(overallAccuracy - (stroopEffect / 10))));
  return {inhibitionScore, overallAccuracy, stroopEffect, congruentAccuracy, incongruentAccuracy};
});

</script>

<template>
  <div v-if="stage === 'instructions'" class="max-w-2xl mx-auto">
    <Card class="bg-white/90 backdrop-blur-sm border-red-200 shadow-lg">
      <CardHeader class="text-center pb-8">
        <div
            class="w-16 h-16 bg-gradient-to-br from-red-600 to-rose-500 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg">
          <StopCircle class="w-8 h-8 text-white"/>
        </div>
        <CardTitle class="text-2xl text-slate-800">{{ t('title') }}</CardTitle>
        <p class="text-slate-600 mt-2">{{ t('description') }}</p>
      </CardHeader>
      <CardContent class="space-y-6">
        <div class="bg-gradient-to-r from-red-50 to-rose-50 rounded-xl p-6 border border-red-100">
          <h3 class="font-semibold text-red-900 mb-4 flex items-center gap-2">
            <Star class="w-5 h-5"/>
            {{ t('instructionsTitle') }}
          </h3>
          <div class="space-y-3 text-slate-700">
            <div class="flex gap-3"><span
                class="w-6 h-6 bg-red-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">1</span>
              <p>{{ t('instruction1') }}</p></div>
            <div class="flex gap-3"><span
                class="w-6 h-6 bg-red-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">2</span>
              <p>
                {{ t('instruction2_1') }} <strong>{{ t('instruction2_strong') }}</strong> {{ t('instruction2_2') }}
              </p></div>
            <div class="flex gap-3"><span
                class="w-6 h-6 bg-red-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">3</span>
              <p>{{ t('instruction3') }}</p></div>
            <div class="flex gap-3"><span
                class="w-6 h-6 bg-red-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">4</span>
              <p>{{ t('instruction4') }}</p></div>
          </div>
        </div>
        <div class="bg-slate-50 rounded-xl p-4 border border-slate-200">
          <h4 class="font-semibold text-slate-700 mb-3 text-center">{{ t('exampleTitle') }}</h4>
          <div class="flex justify-center items-center gap-8">
            <div class="text-center">
              <div class="text-3xl font-bold text-blue-500 mb-2">{{ t('colors.red') }}</div>
              <div class="text-sm text-slate-600">{{ t('example1Word') }}</div>
              <div class="text-sm text-slate-600">{{ t('example1Color') }}</div>
              <div class="text-sm font-semibold text-blue-600 mt-1">{{ t('example1Action') }}</div>
            </div>
            <Target class="w-6 h-6 text-slate-400"/>
            <div class="text-center">
              <div class="text-3xl font-bold text-green-500 mb-2">{{ t('colors.green') }}</div>
              <div class="text-sm text-slate-600">{{ t('example2Word') }}</div>
              <div class="text-sm text-slate-600">{{ t('example2Color') }}</div>
              <div class="text-sm font-semibold text-green-600 mt-1">{{ t('example2Action') }}</div>
            </div>
          </div>
        </div>
        <div class="grid md:grid-cols-3 gap-4">
          <div class="text-center p-4 bg-gradient-to-br from-red-50 to-red-100 rounded-xl border border-red-200">
            <div class="text-2xl font-bold text-red-600 mb-1">{{ TEST_TRIALS }}</div>
            <div class="text-sm text-red-700">{{ t('testTrials') }}</div>
          </div>
          <div class="text-center p-4 bg-gradient-to-br from-rose-50 to-rose-100 rounded-xl border border-rose-200">
            <div class="text-2xl font-bold text-rose-600 mb-1">{{ timeLeft / 60 }}</div>
            <div class="text-sm text-rose-700">{{ t('timeLimit') }}</div>
          </div>
          <div class="text-center p-4 bg-gradient-to-br from-red-50 to-rose-50 rounded-xl border border-red-200">
            <div class="text-2xl font-bold text-slate-600 mb-1">{{ PRACTICE_TRIALS }}</div>
            <div class="text-sm text-slate-700">{{ t('practiceTrials') }}</div>
          </div>
        </div>
        <Button
            class="w-full bg-gradient-to-r from-red-600 to-rose-500 hover:from-red-700 hover:to-rose-600 text-white py-3 text-lg font-semibold shadow-lg hover:shadow-xl transition-all duration-200"
            size="lg"
            @click="handleStartPractice">{{ t('startPractice') }}
        </Button>
      </CardContent>
    </Card>
  </div>

  <div v-else-if="(stage === 'practice' || stage === 'test') && trial" class="max-w-4xl mx-auto space-y-6">
    <div class="flex flex-col sm:flex-row gap-4 items-center justify-between">
      <div class="flex items-center gap-4">
        <Badge class="bg-red-100 text-red-700 border-red-300" variant="outline">
          {{ isPractice ? t('practice') : t('test') }}
          {{ currentTrialIndex + 1 }} / {{ trials.length }}
        </Badge>
        <Badge
            :class="{ 'bg-green-100 text-green-700 border-green-300': trial.condition === 'congruent', 'bg-orange-100 text-orange-700 border-orange-300': trial.condition === 'incongruent', 'bg-blue-100 text-blue-700 border-blue-300': trial.condition === 'neutral' }"
            variant="outline">
          {{ 
            trial.condition === 'congruent' ? t('congruent') : trial.condition === 'incongruent' ? t('incongruent') : t('neutral')
          }}
        </Badge>
        <div v-if="!isPractice" class="flex items-center gap-2 text-slate-600">
          <Trophy class="w-4 h-4"/>
          <span class="font-semibold">{{ score }} / {{ currentTrialIndex }}</span></div>
      </div>
      <div v-if="stage === 'test'" class="flex items-center gap-2">
        <Clock class="w-4 h-4 text-slate-500"/>
        <span :class="['font-mono text-lg font-bold', timeLeft <= 60 ? 'text-red-500' : 'text-slate-700']">{{ 
            Math.floor(timeLeft / 60)
          }}:{{ (timeLeft % 60).toString().padStart(2, '0') }}</span>
      </div>
    </div>
    <Progress :model-value="progress" class="h-2"/>
    <Card class="bg-gradient-to-r from-red-50 to-rose-50 border-red-200">
      <CardContent class="py-4">
        <div class="text-center"><h3 class="text-lg font-semibold text-red-800">{{ t('selectColorPrompt') }}</h3>
        </div>
      </CardContent>
    </Card>
    <Card class="bg-white/90 backdrop-blur-sm border-red-200 shadow-lg">
      <CardContent class="py-16">
        <div class="text-center space-y-12">
          <Transition mode="out-in" name="fade">
            <div :key="trial.id" class="mb-8">
              <div :class="['text-6xl font-bold drop-shadow-lg', COLOR_MAP[trial.color]]">{{ trial.word }}</div>
            </div>
          </Transition>
          <div class="grid grid-cols-2 sm:grid-cols-4 gap-4 max-w-2xl mx-auto">
            <Button v-for="color in COLORS" :key="color"
                    :class="['h-16 text-lg font-semibold shadow-lg transition-all duration-200 text-white', { 'bg-red-500 hover:bg-red-600': color === t('colors.red'), 'bg-blue-500 hover:bg-blue-600': color === t('colors.blue'), 'bg-green-500 hover:bg-green-600': color === t('colors.green'), 'bg-yellow-500 hover:bg-yellow-600': color === t('colors.yellow') }]"
                    @click="() => handleColorResponse(color)">
              {{ color }}
            </Button>
          </div>
        </div>
      </CardContent>
    </Card>
  </div>

  <div v-else-if="stage === 'results'" class="max-w-2xl mx-auto">
    <Card class="bg-white/90 backdrop-blur-sm border-red-200 shadow-xl">
      <CardHeader class="text-center pb-6">
        <div
            class="w-20 h-20 bg-gradient-to-br from-red-600 to-rose-500 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg">
          <Trophy class="w-10 h-10 text-white"/>
        </div>
        <CardTitle class="text-3xl text-slate-800 mb-2">{{ t('testComplete') }}</CardTitle>
        <div class="text-6xl font-bold bg-gradient-to-r from-red-600 to-rose-500 bg-clip-text text-transparent">
          {{ finalResult.inhibitionScore }}
        </div>
        <p class="text-slate-600">{{ t('scoreTitle') }}</p>
      </CardHeader>
      <CardContent class="space-y-6">
        <div class="grid grid-cols-2 gap-4">
          <div class="text-center p-4 bg-gradient-to-br from-red-50 to-red-100 rounded-xl border border-red-200">
            <div class="text-2xl font-bold text-red-600 mb-1">{{ finalResult.overallAccuracy }}%</div>
            <div class="text-sm text-red-700">{{ t('overallAccuracy') }}</div>
          </div>
          <div class="text-center p-4 bg-gradient-to-br from-rose-50 to-rose-100 rounded-xl border border-rose-200">
            <div class="text-2xl font-bold text-rose-600 mb-1">{{ finalResult.stroopEffect }}ms</div>
            <div class="text-sm text-rose-700">{{ t('stroopEffect') }}</div>
          </div>
        </div>
        <div class="space-y-3">
          <div class="flex justify-between items-center p-3 bg-slate-50 rounded-lg"><span
              class="text-slate-600">{{ t('congruentAccuracy') }}</span><span
              class="font-semibold text-slate-800">{{ finalResult.congruentAccuracy }}%</span></div>
          <div class="flex justify-between items-center p-3 bg-slate-50 rounded-lg">
            <span class="text-slate-600">{{ t('incongruentAccuracy') }}</span><span
              class="font-semibold text-slate-800">{{ finalResult.incongruentAccuracy }}%</span></div>
          <div class="flex justify-between items-center p-3 bg-slate-50 rounded-lg"><span
              class="text-slate-600">{{ t('inhibitionIndex') }}</span><span
              class="font-semibold text-slate-800">{{ Math.round(100 - (finalResult.stroopEffect / 10)) }}%</span>
          </div>
        </div>
        <Button
            class="w-full bg-gradient-to-r from-red-600 to-rose-500 hover:from-red-700 hover:to-rose-600 text-white py-3 text-lg font-semibold shadow-lg hover:shadow-xl transition-all duration-200"
            size="lg"
            @click="handleComplete">{{ t('viewDetailedResults') }}
        </Button>
      </CardContent>
    </Card>
  </div>
</template>

<i18n lang="json">
{
  "en": {
    "title": "Inhibitory Control Test",
    "description": "Test your self-control and attention.",
    "instructionsTitle": "Test Instructions",
    "instruction1": "You will see words displayed in different colors.",
    "instruction2_1": "",
    "instruction2_strong": "Ignore the word's meaning",
    "instruction2_2": ", focus only on the display color of the word.",
    "instruction3": "Quickly and accurately click the corresponding color button.",
    "instruction4": "For example: if you see the word \"Blue\" written in red, you should choose red.",
    "exampleTitle": "Example",
    "example1Word": "Word: Red",
    "example1Color": "Display Color: Blue",
    "example1Action": "→ Choose Blue",
    "example2Word": "Word: Green",
    "example2Color": "Display Color: Green",
    "example2Action": "→ Choose Green",
    "testTrials": "Test Trials",
    "timeLimit": "Minute Time Limit",
    "practiceTrials": "Practice Trials",
    "startPractice": "Start Practice",
    "practice": "Practice",
    "test": "Test",
    "congruent": "Congruent",
    "incongruent": "Incongruent",
    "neutral": "Neutral",
    "selectColorPrompt": "Please select the display color of the word, ignoring the word itself.",
    "testComplete": "Test Complete!",
    "scoreTitle": "Inhibitory Control Score",
    "overallAccuracy": "Overall Accuracy",
    "stroopEffect": "Stroop Effect",
    "congruentAccuracy": "Congruent Accuracy",
    "incongruentAccuracy": "Incongruent Accuracy",
    "inhibitionIndex": "Inhibition Index",
    "viewDetailedResults": "View Detailed Results",
    "colors": {
      "red": "Red",
      "blue": "Blue",
      "green": "Green",
      "yellow": "Yellow"
    },
    "neutralWords": {
      "star": "Star",
      "house": "House",
      "table": "Table",
      "flower": "Flower"
    }
  },
  "zh": {
    "title": "抑制控制测试",
    "description": "测试您的自控力和注意力控制能力",
    "instructionsTitle": "测试说明",
    "instruction1": "您将看到不同颜色显示的词语",
    "instruction2_1": "",
    "instruction2_strong": "忽略词语内容",
    "instruction2_2": "，只关注词语的显示颜色",
    "instruction3": "快速准确地点击对应的颜色按钮",
    "instruction4": "例如：看到红色的\"蓝色\"，应该选择红色",
    "exampleTitle": "示例",
    "example1Word": "词语内容：红色",
    "example1Color": "显示颜色：蓝色",
    "example1Action": "→ 选择蓝色",
    "example2Word": "词语内容：绿色",
    "example2Color": "显示颜色：绿色",
    "example2Action": "→ 选择绿色",
    "testTrials": "测试试次",
    "timeLimit": "分钟限时",
    "practiceTrials": "练习试次",
    "startPractice": "开始练习",
    "practice": "练习",
    "test": "测试",
    "congruent": "一致条件",
    "incongruent": "不一致条件",
    "neutral": "中性条件",
    "selectColorPrompt": "请选择词语的显示颜色，忽略词语内容",
    "testComplete": "测试完成！",
    "scoreTitle": "抑制控制能力得分",
    "overallAccuracy": "总准确率",
    "stroopEffect": "Stroop效应",
    "congruentAccuracy": "一致条件准确率",
    "incongruentAccuracy": "不一致条件准确率",
    "inhibitionIndex": "抑制控制指数",
    "viewDetailedResults": "查看详细结果",
    "colors": {
      "red": "红色",
      "blue": "蓝色",
      "green": "绿色",
      "yellow": "黄色"
    },
    "neutralWords": {
      "star": "星星",
      "house": "房子",
      "table": "桌子",
      "flower": "花朵"
    }
  }
}
</i18n>

<style scoped>
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from, .fade-leave-to {
  opacity: 0;
}
</style>
